<template>
  <div>
    <a-form-model layout="horizontal" ref="ruleForm" :model="addScheduleDTO" :rules="validatorRules" v-bind="formItemLayout" > 

      <a-form-model-item label="风险级别" prop="RiskLevel">
      <a-radio-group  v-model="addScheduleDTO.RiskLevel">
              <a-radio :value="1">
                高风险类
              </a-radio>
              <a-radio :value="2">
                中风险类
              </a-radio>
              <a-radio :value="3">
                低风险类
              </a-radio>
      </a-radio-group>
    </a-form-model-item>

    <a-form-model-item label="位置图">
      <a-form-model-item label="住所方位图" prop="livePositionMap" style="font-weight:900;margin-right:220px" >
        <j-upload v-model="addScheduleDTO.livePositionMap" ></j-upload>
        <p style="font-weight:500;">支持扩展名：jpg、png、bmp、svg...</p>
      </a-form-model-item>
      <a-form-model-item label="居住地房屋照片" prop="liveHouseMap" style="font-weight:900;">
        <j-upload v-model="addScheduleDTO.liveHouseMap" ></j-upload>
        <p style="font-weight:500;">支持扩展名：jpg、png、bmp、svg...</p>
      </a-form-model-item>
      <a-form-model-item label="备注" style="font-weight:900;margin-right:550px">
        <a-input  type="textarea" v-model="addScheduleDTO.remark" />
      </a-form-model-item>
    </a-form-model-item>


      
      <div class="plan-item">
      <div class="column-title column-title-required"> 社区康复/社区戒毒工作小组 </div>
      <a-table :columns="WorkGroupColumns" :data-source="WorkGroupTable" >
            <template
              slot="WorkUnit"
              slot-scope="text, record"
            >
              <div>
                <a-form-model-item  :prop="record.key+'WorkUnit'" v-if="record.editable">
                <a-select style="width: 120px;margin: -5px 0"
                  :value="text"
                  @change="e => handleChange(e, record.key,'WorkUnit')"
                  placeholder="请选择"
                  default-value="1"
                  v-model="addScheduleDTO[record.key+'WorkUnit']"
                >
                  <a-select-option value="1">
                    镇（区）挂点领导
                  </a-select-option>
                  <a-select-option value="2">
                    镇（区）禁毒专干
                  </a-select-option>
                  <a-select-option value="3">
                    驻村（居）民警
                  </a-select-option>
                  <a-select-option value="4">
                    村（居）干部
                  </a-select-option>
                  <a-select-option value="5">
                    禁毒志愿者
                  </a-select-option>
                  <a-select-option value="6">
                    直系亲属
                  </a-select-option>
                </a-select>
              </a-form-model-item>
                <template v-else>
                  {{ text==1?'镇（区）挂点领导': text==2?'镇（区）禁毒专干':text==3?'驻村（居）民警':
                text==4?'村（居）干部':text==5?'禁毒志愿者':'直系亲属'}}
                </template>
              </div>
            </template>

            <template
              slot="gender"
              slot-scope="text, record"
            >
              <div>
                <a-form-model-item  :prop="record.key+'gender'" v-if="record.editable">
                <a-select style="width: 120px;margin: -5px 0"
                  :value="text"
                  @change="e => handleChange(e, record.key,'gender')"
                  placeholder="请选择"
                  v-model="addScheduleDTO[record.key+'gender']"
                >
                  <a-select-option value="1">
                    男
                  </a-select-option>
                  <a-select-option value="2">
                    女
                  </a-select-option>
                </a-select>
              </a-form-model-item>
                <template v-else>
                  {{ text==1?'男':'女' }}
                </template>
              </div>
            </template>

            <template
              slot="memberType"
              slot-scope="text, record"
            >
              <div>
                <a-form-model-item  :prop="record.key+'memberType'" v-if="record.editable">
                <a-select style="width: 120px;margin: -5px 0"
                  :value="text"
                  @change="e => handleChange(e, record.key,'memberType')"
                  placeholder="请选择"
                  v-model="addScheduleDTO[record.key+'memberType']"
                >
                  <a-select-option value="1">
                    组长
                  </a-select-option>
                  <a-select-option value="2">
                    成员
                  </a-select-option>
                </a-select>
              </a-form-model-item>
                <template v-else>
                  {{ text==1?'组长':'成员' }}
                </template>
              </div>
            </template>
            <template
              v-for="col in ['name', 'identification', 'age','telphone']"
              :slot="col"
              slot-scope="text, record"
            >
              <div :key="col">
                <a-form-model-item  :prop="record.key+col" v-if="record.editable">
                <a-input
                  style="margin: -5px 0"
                  :value="text"
                  @change="e => handleChange(e.target.value, record.key, col)"
                  placeholder="请输入"
                  v-model="addScheduleDTO[record.key+col]"
                />
              </a-form-model-item>
                <template v-else>
                  {{ text }}
                </template>
              </div>
            </template>
            <template slot="operation" slot-scope="text, record">
              <div class="editable-row-operations">
                <span v-if="record.editable">
                  <a @click="() => save(record.key)" style="margin-right:10px">保存</a>
                  <a-popconfirm title="确定取消吗?" @confirm="() => cancel(record.key)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span v-else>
                  <a :disabled="editingKey !== ''" @click="() => edit(record.key)" style="margin-right:10px">编辑</a>
                  <a-popconfirm
                  v-if="WorkGroupTable.length"
                  title="确定删除吗?"
                  @confirm="() => onDelete(record.key)"
                >
                  <a href="javascript:;" :disabled="editingKey !== ''">删除</a>
                </a-popconfirm>
                </span>
              </div>
            </template>
          </a-table>
      <a-button block size="large" @click="handleAdd" style="margin-top:20px;"> +添加 </a-button>
    
    </div>
      <div class="plan-item">
        <div class="column-title column-title-required"> 计划类型（必填） </div>
        <z-form-item :datas="fieldArr1" :form="addScheduleDTO" :rules="validatorRules" :gutter="0" />
      </div>
      <div class="plan-item">
        <div class="column-title column-title-required">
          行动计划表（必填）
          <a-tooltip placement="topLeft" title="时间安排时段内，如有相关数据，系统会自动判定为已完成，反之则为未完成。">
            <a-icon type="exclamation-circle" />
          </a-tooltip>
        </div>
        <a-table :columns="PlanColumns" :data-source="PlanTable" >
            <template
              slot="PlanTime"
              slot-scope="text, record"
            >
              <div>
                <a-form-model-item  :prop="record.key+'PlanTime'" v-if="record.editable">
                <a-range-picker
                  style="margin: -5px 0"
                  :value="text"
                  @change="e => handleChange1(e, record.key,'PlanTime')"
                  v-model="addScheduleDTO[record.key+'PlanTime']"
                />
              </a-form-model-item>
                <template v-else>
                  <div v-if="!text"></div>
                  <div v-else>{{ timestampToTime(text[0])+' '+'~'+' '+timestampToTime(text[1])}}</div>
                </template>
              </div>
            </template>
            
            <template
              slot="typeIntervention"
              slot-scope="text, record"
            >
              <div>
                <a-form-model-item  :prop="record.key+'typeIntervention'" v-if="record.editable">
                <a-select style="width: 120px;margin: -5px 0"
                :value="text"
                @change="e => handleChange1(e, record.key,'typeIntervention')"
                placeholder="请选择"
                v-model="addScheduleDTO[record.key+'typeIntervention']"
              >
              <a-select-option value="1">
                尿液检测
              </a-select-option>
              <a-select-option value="2">
                毛发检测
              </a-select-option>
              <a-select-option value="3">
                定期访谈	
              </a-select-option>
              <a-select-option value="4">
                帮教谈心
              </a-select-option>
              <a-select-option value="5">
                定期报告
              </a-select-option>
              <a-select-option value="6">
                社区活动	
              </a-select-option>
              <a-select-option value="7">
                小组活动
              </a-select-option>
              <a-select-option value="8">
                帮扶救助
              </a-select-option>
              <a-select-option value="9">
                职业技能培训
              </a-select-option>
              <a-select-option value="10">
                就业安置	
              </a-select-option>
              <a-select-option value="11">
                法律援助
              </a-select-option>
              <a-select-option value="12">
                心理咨询	
              </a-select-option>
              <a-select-option value="13">
                美沙酮治疗
              </a-select-option>
              <a-select-option value="14">
                特殊人员处置申请
              </a-select-option>
            </a-select>
          </a-form-model-item>
                <template v-else>
                  {{ text==1?'尿液检测':text==2?'毛发检测':text==3?'定期访谈':text==4?'帮教谈心':
                  text==5?'定期报告':text==6?'社区活动':text==7?'小组活动':text==8?'帮扶救助':
                  text==9?'职业技能培训': text==10?'就业安置':text==11?'法律援助':text==12?'心理咨询':
                  text==13?'美沙酮治疗':'特殊人员处置申请'}}
                </template>
              </div>
            </template>

            <template
              slot="taskVolume"
              slot-scope="text, record"
            >
              <div>
                <a-form-model-item  :prop="record.key+'taskVolume'" v-if="record.editable">
                <a-input
                  style="margin: -5px 0"
                  :value="text"
                  @change="e => handleChange1(e.target.value, record.key,'taskVolume')"
                  v-model="addScheduleDTO[record.key+'taskVolume']"
                />
              </a-form-model-item>
                <template v-else>
                  {{ text }}
                </template>
              </div>
            </template>

            <template slot="operation1" slot-scope="text, record">
              <div class="editable-row-operations">
                <span v-if="record.editable">
                  <a @click="() => save1(record.key)" style="margin-right:10px">保存</a>
                  <a-popconfirm title="确定取消吗?" @confirm="() => cancel1(record.key)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span v-else>
                  <a :disabled="editingKey1 !== ''" @click="() => edit1(record.key)" style="margin-right:10px">编辑</a>
                  <a-popconfirm
                  v-if="PlanTable.length"
                  title="确定删除吗?"
                  @confirm="() => onDelete1(record.key)"
                >
                  <a href="javascript:;" :disabled="editingKey1 !== ''">删除</a>
                </a-popconfirm>
                </span>
              </div>
            </template>
          </a-table>
        <a-button block size="large" @click="handleAdd1"  style="margin-top:20px;"> +添加 </a-button>
      </div>
      <div class="plan-item">
        <div class="column-title"> 预计困难/风险及预案 </div>
        <z-form-item :datas="fieldArr2" :form="addScheduleDTO" :rules="validatorRules" :gutter="0" />
      </div>
      <div class="plan-item">
        <div class="column-title"> 资源保障 </div>
        <z-form-item :datas="fieldArr3" :form="addScheduleDTO" :rules="validatorRules" :gutter="0" />
      </div>
    </a-form-model>
  </div>
</template>
<script>
// import EditableCell from './editableCell'
const WorkGroupColumns = [
  {
    title: '成员类型',
    dataIndex: 'memberType',
    // width: '25%',
    scopedSlots: { customRender: 'memberType' },
  },
  {
    title: '工作单位及职务或身份',
    dataIndex: 'WorkUnit',
    // width: '15%',
    scopedSlots: { customRender: 'WorkUnit' },
  },
  {
    title: '姓名',
    dataIndex: 'name',
    // width: '40%',
    scopedSlots: { customRender: 'name' },
  },
  {
    title: '身份证号',
    dataIndex: 'identification',
    // width: '40%',
    scopedSlots: { customRender: 'identification' },
  },
  {
    title: '性别',
    dataIndex: 'gender',
    // width: '40%',
    scopedSlots: { customRender: 'gender' },
  },
  {
    title: '年龄',
    dataIndex: 'age',
    // width: '40%',
    scopedSlots: { customRender: 'age' },
  },
  {
    title: '联系方式',
    dataIndex: 'telphone',
    // width: '40%',
    scopedSlots: { customRender: 'telphone' },
  },
  {
    title: '操作',
    width: '15%',
    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' },
  },
];
const PlanColumns = [
  {
    title: '计划时间',
    dataIndex: 'PlanTime',
    // width: '25%',
    scopedSlots: { customRender: 'PlanTime' },
  },
  {
    title: '介入类型',
    dataIndex: 'typeIntervention',
    // width: '15%',
    scopedSlots: { customRender: 'typeIntervention' },
  },
  {
    title: '任务量',
    dataIndex: 'taskVolume',
    // width: '40%',
    scopedSlots: { customRender: 'taskVolume' },
  },
  {
    title: '操作',
    dataIndex: 'operation1',
    scopedSlots: { customRender: 'operation1' },
  },
];
const WorkGroupTable = [];
const PlanTable = [];
export default {
  // components: { EditableCell },
  props: ['current', 'value','huancun'],
  data() {
    this.cacheData = WorkGroupTable.map(item => ({ ...item }));
    this.cacheData1 = PlanTable.map(item => ({ ...item }));
    return {
      WorkGroupTable,
      PlanTable,
      WorkGroupColumns,
      PlanColumns,
      editingKey: '',
      editingKey1: '',
      count:0,
      count1:200,
      model: {},
      
      // helpGroupListCacheDatas: [],
      // 行动计划表-数组集
      // actionPlansCacheDatas: [],
      // 计划类型、预计困难/风险及预案、资源保障-对象
      addScheduleDTO: {},
      columnsRules: {
        memberType:[ { required: true, message: '请选择成员类型' }],
        post:[ { required: true, message: '请选择工作单位及职务或身份' }],
        name:[ { required: true, message: '请输入姓名' }],
        identification:[ 
          { required: true, message: '请输入身份证号' },
          { reg: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号' },
        ],
        gender:[ { required: true, message: '请选择性别' }],
        age:[ { required: true, message: '请输入年龄' }],
        telphone:[ 
          { required: true, message: '请输入联系方式' },
          { reg: /^(\+86)?1[3456789]\d{9}$/, message: '请输入正确的联系方式' },
        ],
        planTime:[ { required: true, type: 'array', message: '请选择计划时间' }],
        typeIntervention:[ { required: true, message: '请选择介入类型' }],
        taskVolume:[ { required: true, message: '请输入任务量' }]
      },
      formItemLayout: {
        labelCol: { span: 3 },
        wrapperCol: { span: 18 }
      },
      fieldArr1: [
        {label: '计划类型', prop: 'planType', tagType: 'dict-select', dictOptions: [{ text: '帮教计划', value:'1' },{ text: '帮扶计划', value:'2' }]},
        {label: '计划内容', prop: 'planContent', tagType: 'textarea'},
      ],
      fieldArr2: [
        {label: '预计困难/风险', prop: 'risk', tagType: 'textarea',},
        {label: '预案', prop: 'reservePlan', tagType: 'textarea'},
      ],
      fieldArr3: [
        {label: '投入资源', prop: 'inputResourses', tagType: 'textarea',},
        {label: '预算', prop: 'budget', tagType: 'textarea'},
      ],
      
      validatorRules: {
        RiskLevel:[ { required: true, message: '请选择风险级别' }],
        livePositionMap:[ { required: true, message: '请上传住所方位图' }],
        liveHouseMap:[ { required: true, message: '请上传居住地房屋照片' }],
        planType:[ { required: true, message: '请选择计划类型' }],
        planContent:[ { required: true, message: '请输入计划内容' }],
      }
    };
  },
  
  watch: {
    addScheduleDTO:{
      immediate:true,
      deep:true,
      handler(val){
        // let {liveHouseMap,livePositionMap,remark} = val
        this.helpFormModel(val)
      }
    },
    PlanTable:{
      immediate:true,
      deep:true,
      handler(val){
        this.PlanTabledata(val)
      }
    },
    WorkGroupTable:{
      immediate:true,
      deep:true,
      handler(val){
        this.WorkGroupTabledata(val)
      }
    },
    huancun:{
      immediate:true,
      deep:true,
      handler(val){
        console.log(val);
        if(val.helpform){
          this.addScheduleDTO = val.helpform
        }
        this.WorkGroupTable = val.workGroupAndPersonDTO.sjskTeamerList?val.workGroupAndPersonDTO.sjskTeamerList:[]
        this.PlanTable = val.addScheduleDTO.actionPlans?val.addScheduleDTO.actionPlans:[]
      }
    },
    
  },
  created() {
    // this.$set(this.addScheduleDTO, 'planType', '1')
    // this.helpGroupListCacheDatas = this.helpGroupListDatas.map((item) => ({ ...item }));
  },
  methods: {
    timestampToTime(timestamp) {
      if (timestamp === 0 || timestamp == null) {
        return ''
      } 
      else {
        var date = new Date(Date.parse(timestamp))
        var Y = date.getFullYear() + '-'
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
        return Y + M + D
      }
    },
    helpFormModel(val){
      this.$emit('helpFormModel',val)
    },
    PlanTabledata(val){
      for(let i=0;i<val.length;i++){
        val[i].planStartTime = val[i].PlanTime?this.timestampToTime(val[i].PlanTime[0]):''
        val[i].planEndTime = val[i].PlanTime?this.timestampToTime(val[i].PlanTime[1]):''
        // delete val[i].PlanTime
        
      }
      this.$emit('PlanTabledata',val)
    },
    WorkGroupTabledata(val){
      this.$emit('WorkGroupTabledata',val)
    },
    handleChange(value, key, column) {
      const newData = [...this.WorkGroupTable];
      const target = newData.find(item => key === item.key);
      if (target) {
        target[column] = value;
        this.WorkGroupTable = newData;
      }
    },
    handleChange1(value, key, column) {
      const newData = [...this.PlanTable];
      const target = newData.find(item => key === item.key);
      if (target) {
        target[column] = value;
        this.PlanTable = newData;
      }
    },
    edit(key) {
      const newData = [...this.WorkGroupTable];
      const target = newData.find(item => key === item.key);
      this.editingKey = key;
      if (target) {
        target.editable = true;
        this.WorkGroupTable = newData;
      }
    },
    edit1(key) {
      const newData = [...this.PlanTable];
      const target = newData.find(item => key === item.key);
      this.editingKey1 = key;
      if (target) {
        target.editable = true;
        this.PlanTable = newData;
      }
    },
    save(key) {
      this.$nextTick(() => {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              const newData = [...this.WorkGroupTable];
              const newCacheData = [...this.cacheData];
              const target = newData.find(item => key === item.key);
              const targetCache = newCacheData.find(item => key === item.key);
              if (target && targetCache) {
                delete target.editable;
                this.WorkGroupTable = newData;
                Object.assign(targetCache, target);
                this.cacheData = newCacheData;
              }
              this.editingKey = '';
            } 
            else { 
              return false;
            }
          })
        })
    },
    save1(key) {
      this.$nextTick(() => {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              const newData = [...this.PlanTable];
              const newCacheData = [...this.cacheData1];
              const target = newData.find(item => key === item.key);
              const targetCache = newCacheData.find(item => key === item.key);
              if (target && targetCache) {
                delete target.editable;
                this.PlanTable = newData;
                Object.assign(targetCache, target);
                this.cacheData1 = newCacheData;
              }
              this.editingKey1 = '';
            } 
            else { 
              return false;
            }
          })
        })
    },
    cancel(key) {
      const newData = [...this.WorkGroupTable];
      const target = newData.find(item => key === item.key);
      this.editingKey = '';
      if (target) {
        Object.assign(target, this.cacheData.find(item => key === item.key));
        delete target.editable;
        this.WorkGroupTable = newData;
      }

    },
    cancel1(key) {
      const newData = [...this.PlanTable];
      const target = newData.find(item => key === item.key);
      this.editingKey1 = '';
      if (target) {
        Object.assign(target, this.cacheData1.find(item => key === item.key));
        delete target.editable;
        this.PlanTable = newData;
      }
    },
    onDelete(key){
      this.WorkGroupTable = this.WorkGroupTable.filter(item => item.key !== key);
    },
    onDelete1(key){
      this.PlanTable = this.PlanTable.filter(item => item.key !== key);
    },
    handleAdd() {
      this.$nextTick(() => {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              this.count = this.WorkGroupTable.length
              const newData = {
                key: this.count,
              };
              this.WorkGroupTable.unshift(newData)
              this.cacheData = this.WorkGroupTable.map(item => ({ ...item }));
              this.edit(this.count)
              this.validatorRules[this.count+'memberType'] = [ { required: true, message: '请选择', trigger: 'blur' } ]
              this.validatorRules[this.count+'WorkUnit'] = [ { required: true, message: '请选择', trigger: 'blur' } ]
              this.validatorRules[this.count+'name'] = [ { required: true, message: '请输入', trigger: 'blur' } ]
              this.validatorRules[this.count+'identification'] = [ { required: true, message: '请输入', trigger: 'blur' } ]
              this.validatorRules[this.count+'gender'] = [ { required: true, message: '请选择', trigger: 'blur' } ]
              this.validatorRules[this.count+'age'] = [ { required: true, message: '请输入', trigger: 'blur' } ]
              this.validatorRules[this.count+'telphone'] = [ { required: true, message: '请输入', trigger: 'blur' } ]
              this.count = this.count + 1;
            } 
            else { 
              alert('执行此操作前请先将表单/表格填写完毕');
              return false;
            }
          })
        })
      
    },
    handleAdd1() {
      this.$nextTick(() => {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              this.count1 = this.PlanTable.length+200
              const newData = {
                key: this.count1,
              };
              this.PlanTable.unshift(newData)
              this.cacheData1 = this.PlanTable.map(item => ({ ...item }));
              this.edit1(this.count1)
              this.validatorRules[this.count1+'PlanTime'] = [ { required: true, message: '请选择', trigger: 'blur' } ]
              this.validatorRules[this.count1+'typeIntervention'] = [ { required: true, message: '请选择', trigger: 'blur' } ]
              this.validatorRules[this.count1+'taskVolume'] = [ { required: true, message: '请输入', trigger: 'blur' } ]
              this.count1 = this.count1 + 1;
            } 
            else { 
              alert('执行此操作前请先将表单/表格填写完毕');
              return false;
            }
          })
        })
    },
    
    inRegExp(recordValue, column) {
      let editableColumns = this.typeKey+'EditableColumns'
      let bool = false
      // 单个事件校验
      if (column && this.columnsRules[column]) {
        let rules = this.columnsRules[column]
        let value = recordValue
        if(!value || (value && value.length===0)) {
          this.$message.error({content: rules[0].message, key: column, duration: 3})
          bool = true
        }
        if(value && rules.length>1 && !rules[1].reg.test(value)) {
          this.$message.error({content: rules[1].message, key: column, duration: 3})
          bool = true
        }
      }
      // 保存事件校验
      if(!column) {
        let record = recordValue, props = []
        const { key } = record
        for (const keys in record) {
          let rules = this.columnsRules[keys]
          if(record[keys] && rules && rules.length>1) {
            let b = rules[1].reg.test(record[keys])
            if(b) props.push(keys)
          } else if(record[keys] && (!rules || rules.length===1)) {
            props.push(keys)
          }
        }
        let data = this[editableColumns].filter(item => props.indexOf(item.prop) === -1) // 过滤不满足条件的值
        let title = data.map(v=> { if(v.prop !== 'action') { return v.title } }).filter(obj => obj !== undefined)
        if(title && title.length>0) {
          this.$message.error({content: title.toString()+'校验不通过，请完善有误的数据', key: editableColumns+key, duration: 3})
          bool = true
        }
      }
      return bool
    }
   
  }
}
</script>
<style lang="less" scoped>
.plan-item{
  margin-bottom: 26px;
  padding-bottom: 26px;
  border-bottom: 1px #ccc dashed;
  &:last-child{
    border-bottom: 0;
  }
}
.column-title {
  margin-bottom: 20px;
  font-weight: bold;
  &.column-title-required {
    &::before {
      content: "*";
      color: #f5222d;
    }
  }
}
</style>
